import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  const token = store.getters.token
  if (token) {
    // 有token
    if (to.path === '/login') {
      next(false)
      NProgress.done()
    } else {
      next()
      // 没有 就调用 获取
      if (!store.getters.name) {
        store.dispatch('user/getUserInfoActions')
      }
      NProgress.done()
    }
  } else {
    // 无token
    if (whiteList.includes(to.path)) {
      // 在白名单
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

// 后置守卫
router.afterEach((to, from) => {
  // finish progress bar
  document.title = getPageTitle(`${to.meta.title}`)
  NProgress.done()
})
